<?php
/**
 * Created by PhpStorm.
 * User: Mars.Li
 * Date: 2015/6/25
 * Time: 16:22
 */

/**
 * 通过id 获取分组名称
 * @param $id     节点id
 * @return string  分组名称
 */
 function getNodeGroupName( $id ) {
    if (empty ( $id )) {
        return '未分组';
    }
    if (isset ( $_SESSION ['nodeGroupList'] )) {
        return $_SESSION ['nodeGroupList'] [$id];
    }
    $Group = D ( "Group" );
    $list = $Group->getField ( 'id,title' );
    $_SESSION ['nodeGroupList'] = $list;
    $name = $list [$id];
    return $name;
}

/**
 * 通过id 获取节点名称
 * @param $id
 * @return string
 */
function getNodeName( $id ) {
    if (empty ( $id )) {
        return '不存在节点';
    }
    $map['id']=$id;
    $name	=	M('Node')->where($map)->field('title')->find();
    return $name['title'];
}

/**
 * 获取状态 移植dwz系统
 * @param $status
 * @param bool $imageShow
 * @return string
 */
function getStatus($status, $imageShow = false) {
    switch ($status) {
        case 0 :
            $showText = '禁用';
            $showImg = '<IMG SRC="' . __PUBLIC__ . '/Images/locked.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="禁用">';
            break;
        case 2 :
            $showText = '待审';
            $showImg = '<IMG SRC="' . __PUBLIC__ . '/Images/prected.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="待审">';
            break;
        case - 1 :
            $showText = '删除';
            $showImg = '<IMG SRC="' . __PUBLIC__ . '/Images/del.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="删除">';
            break;
        case 1 :
        default :
            $showText = '正常';
            $showImg = '<IMG SRC="' . __PUBLIC__ . '/Images/ok.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="正常">';

    }
    return ($imageShow === true) ?  $showImg  : $showText;

}

/**
 * 获取下拉选项的label
 * @param $option_value   对应的值
 * @param array $options  数据源
 * @return mixed
 */
function getOptionsLabel($option_value,array $options)
{
    foreach ($options as $key=>$val){
        if($val['value']==$option_value) {
            if(!empty($val['label'])) return L($val['label']);
            return $val['label'];
        }
    }
    return $option_value;
}


/**
 * 生成一个下拉选项集合
 * @param array $values   数据源 要生成的数据
 * @param string $value   当前选中的值
 * @return string       返回html
 */
function renderOptions(array $values,$value="",$tran = false)
{
    $html='<option value="">'.L("choose").'</option>';
    if(!empty($values)){
        foreach ($values as $key=>$val){
            $select="";
            if($val['value']==$value)       $select = " selected";
            if($val['label']!=''&&!is_numeric($val['label']) && $tran)
                $html.='<option value="'.$val['value'].'" '.$select.'>'.L($val['label']).'</option>';
            else
                $html.='<option value="'.$val['value'].'" '.$select.'>'.$val['label'].'</option>';
        }
    }
    return $html;
}


/**
 * 通过部门id 获取部门信息 参数为空则获取所有部门信息
 * @param string $department_id
 * @return array
 */
function getDepartment($department_id="")
{
    $department = array();
    $data=M("Department")->select();
    foreach ($data as $key=>$val){
        $department[]=array("value"=>$val['id'],"label"=>$val['dept_name']);
    }
    if($department_id){
        foreach ($department as $val){
            if($val['value']==$department_id) return $val['label'];
        }
    }
    return $department;
}

/**
 * 显示状态
 * @param $status  显示状态类型
 * @param $id       条目id
 * @return string  返回html
 */
function showStatus($status, $id) {

    switch ($status) {
        case 0 :
            $info = '<a href="'.__SELF__ .'/resume/id/' . $id . '" class="ajax-get" >恢复</a>';
            break;
        case 2 :
            $info = '<a href="'.__SELF__.'/pass/id/' . $id . '" class="ajax-get" >批准</a>';
            break;
        case 1 :
            $info = '<a href="'.__SELF__.'/forbid/id/' . $id . '" class="ajax-get" >禁用</a>';
            break;
        case - 1 :
            $info = '<a href="'.__SELF__.'/recycle/id/' . $id . '" class="ajax-get" >还原</a>';
            break;
    }
    return $info;
}


function getGroupName($id) {
    if ($id == 0) {
        return '无上级组';
    }
    if ($list = F ( 'groupName' )) {
        return $list [$id];
    }
    $dao = D ( "Role" );
    $list = $dao->select ( array ('field' => 'id,name' ) );
    foreach ( $list as $vo ) {
        $nameList [$vo ['id']] = $vo ['name'];
    }
    $name = $nameList [$id];
    F ( 'groupName', $nameList );
    return $name;
}

/**
 * 获取用户表字段
 * @param string $userid 用户id 默认为当前登陆用户
 * @param string $field  返回对应的字段
 * @return mixed
 */
function getUserName($userid="",$field = 'account',$cache = true)
{
    if(!$userid) $userid =  $_SESSION[C('USER_AUTH_KEY')];
    $User = M("user");
    return $User->cache($cache)->where('id='.$userid)->getField($field);
}


/**
 * 创建树形节点菜单
 * @param $list     数据源
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param int $root
 * @return array
 */
function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0)
{
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if(isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 密码加密
 * @param $password
 * @param string $type
 * @return string
 */
function pwdHash($password, $type = 'md5') {
    return hash ( $type, $password );
}



/**
 * @return string 返回头像图片保存路径
 */
 function getAvatarPath()
{

    return __ROOT__ ."/Public/Images/".getUserName()."/";
}

/**
 *  视频上传目录
 */
function getVideoPath($video_id) {
    return __ROOT__.'/Public/Images/Video/'.$video_id.'/';
}

/**
 *  图像上传目录
 */
function getImagePath() {
    return '/Public/Images/picturelibrary/';
}


/**
 *  常用链接icon
 */
function getLinkPath() {
    return  __ROOT__.'/Public/Images/Link/';
}

/**
 * 发送邮件
 * @param $to
 * @param $name
 * @param string $subject
 * @param string $body
 * @param null $attachment
 * @return bool|string
 * @throws \Exception
 * @throws \phpmailerException
 */
function sendEmail($to, $name, $subject = '', $body = '', $attachment = null) {

    $config = C('THINK_EMAIL');
    Vendor('phpmailer.class#phpmailer'); //从PHPMailer目录导class.phpmailer.php类文件
    $mail             = new \PHPMailer(); //PHPMailer对象
    $mail->CharSet    = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();  // 设定使用SMTP服务
    $mail->SMTPDebug  = 1;                     // 关闭SMTP调试功能
    // 1 = errors and messages
    // 2 = messages only
    $mail->SMTPAuth   = true;                  // 启用 SMTP 验证功能
    //$mail->SMTPSecure = 'ssl';                 // 使用安全协议
    $mail->Host       = $config['SMTP_HOST'];  // SMTP 服务器
    $mail->Port       = $config['SMTP_PORT'];  // SMTP服务器的端口号
    $mail->Username   = $config['SMTP_USER'];  // SMTP服务器用户名
    $mail->Password   = $config['SMTP_PASS'];  // SMTP服务器密码
    $mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
    $replyEmail       = $config['REPLY_EMAIL']?$config['REPLY_EMAIL']:$config['FROM_EMAIL'];
    $replyName        = $config['REPLY_NAME']?$config['REPLY_NAME']:$config['FROM_NAME'];
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject    = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($to, $name);
    if(is_array($attachment)){ // 添加附件
        foreach ($attachment as $file){
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}

/**
 * @param $id
 * @return mixed
 * 获取ets部门名称
 */
function getDepartmentName($id) {
   $result = D('Department')->field('name')->where('department_id='.$id)->find();
    return $result['name'];
}

/**
 * 获取登陆帐号的 权限组
 * @param string $userid
 * @return string   customer 用户组  core 管理组
 */
function  getSiginRoleName($userid = '') {
    if(!$userid) $userid =  $_SESSION[C('USER_AUTH_KEY')];
    //获取用户组 userid
    $customerList = D('Role')->getGroupUserLists(1);
    //获取内部组 userid
    $corelist = D('Role')->getGroupUserLists(2);
    $rs = 'boss';
    if (in_array($userid,$customerList)) {
        $rs = 'customer';
    }
    if(in_array($userid,$corelist)){
        $rs = 'core';
    }
    return $rs;
}

//获取视频分类
function getVideoCategory() {
    $data = M('video_category')->select();
    $result = array();
    foreach ($data as $item) {
        $result[] = array('label'=>$item['cat_name'],'value'=>$item['id']);
    }
    return $result;
}

//获取视频主要人物
function getMainPeople($videoid){
    $map['video_id'] = $videoid;
    $map['attr_id'] = 2;
    $data = M('video_attr')->where($map)->getField('attr_value',true);
    return $data;
}


/**
 * 移植ets系统  by mars
 * 根据币种获取其转化为RMB的汇率,默认获取USD转RMB币种的汇率。
 * @author Jimmy
 * @date 2014-08-05 17:08:11
 *
 * updated 添加日期参数：有时候做单据的时候需要获取当初单据创建时候的汇率，比如：换货单。
 * @param string $created_at 单据的创建日期
 * @author Jimmy
 * @date 2015-02-13 15:41:11
 */
function getCurVal($created_at){
    //同步获取汇率
    $where['iYear']=$created_at?date('Y',strtotime($created_at)):date('Y');
    $where['cdate']=$created_at?date('n',strtotime($created_at)):date('n');
    $where['cexch_name']= 'USD';
    $modelVendor=new \Admin\Model\VendorModel('exch');
    $res=$modelVendor->cache(true)->where($where)->field('nflat')->find();
    return $res['nflat'];
}

/**
 *  通过用户名获取ets系统密码
 */
function getEtsPwdByUserName($username){
   return D('Userets')->where('account="'.$username.'"')->getField('password');
}

function getLinkUrlById($id) {
    return M('link')->where('id='.$id)->getField('url');
}

/**
 * 获取ets登录地址
 * @param $userkey
 * @return mixed|string
 */
function getEtsLoginUrl($userkey) {
    $pwd = getEtsPwdByUserName($userkey);
    $url = getLinkUrlById(6);
    if ($pwd) {
        return  $url.'/Public/checkLogin?url='.urlencode($url).'&account='.$userkey.'&password='.$pwd;
    }else {
        return $url;
    }

}

/**
 * 获取系统邮箱后缀
 */
function getEmailSuffix($default = false,$id = 0){
    if ($default){
        $where['status'] = 1;
        if ($id){
            $where['id'] = $id;
        }else {
            $where['is_default'] = 1;
        }
        return M('email_setings')->where($where)->getField('mailbox_suffix');
    }else {
       $data = M('email_setings')->field('mailbox_suffix,id')->where('status=1')->select();
       $result = array();
       foreach ($data as $v) {
           $result[] = array(
               'label' => $v['mailbox_suffix'],
               'value' => $v['id'],
           );
       }
    }
   return $result;
}

/**
 * 格式化首页邮箱标题
 * @param $val
 * @return mixed
 */
 function foatmack ($val) {
    $matchs = array();
    preg_match('{\\"(.*?)\\"}s',$val,$matchs);
    return $matchs[1];
}

/**
 * 添加邮箱模版
 * @return string
 */
function getAddEmailTemplate() {
    $options = renderOptions(getEmailSuffix(),"");
    $html = '<div class="email-item email-item2" style="margin-bottom:50px;">'.
    '<div class="input-group col-md-10 pull-left input-group-1 input-parent">'.
    '<input type="text" class="form-control child-input" name="email[]" aria-label="...">'.
    '</div>'.
    '<div class="input-group-btn input-group-btn1 child-btn">'.
    '<select name="mailbox_suffix[]" class="form-control mail-select  mail-sufix select-child" style="width:45%">'.$options.
    '</select>'.
    '</div>'.
    '<div class="input-group col-md-2 col-sm-2 pull-left child-inputw">'.
    '<div class="input-group-btn input-group-btn2 child-inputs" style="width:35%">'.
    '<select name="is_main[]" class="form-control mail-select mail-default child-selects">'.
    '<option value="0">次邮箱</option>'.
    '<option value="1">主邮箱</option>'.
    '</select>'.
    '</div>'.
    '<a href="javascript:;"  class="btn button btn-default email-ajaxremove email-ajaxremove-btn email-ajaxremove-btnon"><i class="fa fa-remove"></i></a>'.
    '</div>'.
    '</div>';
    return $html;
}

/**
 * 添加域名前缀
 * @param string $file
 * @return string
 */
function getHttpHost($file = '') {
    $link =  'http://'.$_SERVER['HTTP_HOST'].'/'.__ROOT__;
    if ($file){
        $link .= $file;
    }
  return $link;
}

/**
 * 获取表报单元模版
 * @param $reportName   表报名称
 * @return string       html
 */
function getUnitHtml($reportName) {

    $html ='<label>'.L('单位').'</label>:';

    if (LANG_SET == 'en-us'):
        $html .=' <a href="javascript:;" class="text-black" >'.L('元').'</a>';
    else:
        $reportName = $reportName.'_unit';
    if (!isset($_SESSION[$reportName])) {
        $w = 'javascript:;';
        $w_class = 'text-black';
        $r = __APP__.'/Reports/index/'.$reportName.'/0';
    } else {
        if ($_SESSION[$reportName] == 0) {
            $w = __APP__.'/Reports/index/'.$reportName.'/1';
            $r = 'javascript:;';
            $r_class = 'text-black';
        } else {
            $w = 'javascript:;';
            $w_class = 'text-black';
            $r = __APP__.'/Reports/index/'.$reportName.'/0';
        }

    }
        $html .='<a href="'.$w.'" class="'.$w_class.'" >'.L('万').'</a>/';
        $html .='<a href="'.$r.'" class="'.$r_class.'" >'.L('元').'</a>';
    endif;

    return $html;
}

/**
 * 删除文件
 * @param $file
 */
function  clearFile($file) {
    if (is_array($file)){
        foreach ($file as $f) {
            if(file_exists($f))  @unlink($f);
        }
    } else  {
      if(file_exists($file))  @unlink($file);
    }
}

/**
 * 图片库属性模版
 * @param $attributelist
 * @return string
 */
function  getPicurteAttributeListHtml ($attributelist) {
    $html = '';
   foreach ($attributelist as $key => $item ) {
        foreach ($item['attr_values'] as $v) {
            $html .= " <li class='pull-left'>";
            $class = '';
            if($_SESSION[$item['attr_name']] == $item['attr_id']): $class = 'active'; endif;
            $val = $v["value"];
            $id = $item["attr_id"];
            $url =  "__APP__/Picture/index/attribute_value_id/$val/attribute_id/$id";
            $label = $v["label"];
            $html .= " <a href='$url' class='$class text-black'>'$label'</a></li>";
         }
   }
    return $html;
}

/**
 * @param $file     要读取的xls路径
 * @return array 存在数据 返回整理后的数据 否则返回false
 * 读取xsl文件
 */
function readExcel($file){
    Vendor('phpexcel.PHPExcel');
    $PHPExcel = new \PHPExcel();
    $PHPReader = new \PHPExcel_Reader_Excel2007();
    if(!$PHPReader->canRead($file)){
        $PHPReader = new \PHPExcel_Reader_Excel5();
        if(!$PHPReader->canRead($file)){
            return false;
        }

    }
    $PHPExcel = $PHPReader->load($file);
    $SheetCount = $PHPExcel->getSheetCount();
    $array = array();
    for($i=0;$i<$SheetCount;$i++){

        $currentSheet = $PHPExcel->getSheet($i);
        $allColumn = ExcelChange($currentSheet->getHighestColumn());
        $allRow = $currentSheet->getHighestRow();
        $array[$i]["Title"] =  $currentSheet->getTitle();
        $array[$i]["Cols"] = $allColumn;
        $array[$i]["Rows"] = $allRow;
        $arr = array();
        for($currentRow = 1 ;$currentRow<=$allRow;$currentRow++){
            $row = array();
            for($currentColumn=0;$currentColumn<$allColumn;$currentColumn++){
                $row[$currentColumn] = (string)$currentSheet->getCellByColumnAndRow($currentColumn,$currentRow)->getValue();
            }
            $arr[$currentRow] = $row;
        }
        $array[$i]["Content"] = $arr;
    }
    return $array;
}

function ExcelChange($str)
{
    $len = strlen($str)-1;
    $num = 0;
    for($i=$len;$i>=0;$i--){
        $num += (ord($str[$i]) - 64)*pow(26,$len-$i);
    }
    return $num;
}

/**
 * 随机生成密码
 * @param int $length 需要的密码长度
 * @return string
 */
function make_password( $length = 6 )
{
    // 密码字符集，可任意添加你需要的字符
    $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
        'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',
        't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',
        'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',
        'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!',
        '@','#', '$', '%', '^', '&', '*', '(', ')', '-', '_',
        '[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',',
        '.', ';', ':', '/', '?', '|');

    // 在 $chars 中随机取 $length 个数组元素键名
    $keys = array_rand($chars, $length);

    $password = '';
    for($i = 0; $i < $length; $i++)
    {
        // 将 $length 个数组元素连接成字符串
        $password .= $chars[$keys[$i]];
    }

    return $password;
}